const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-session')
const baseConfig = require('./config/base-config')
const index = require('./routes/index')
const users = require('./routes/users')
const news = require('./routes/apis/news')
const passport = require('./middleware/passport')
const cors = require('koa2-cors')//使用cors中间件

//session
app.keys = ['some secret hurr'];
app.use(session(baseConfig.seesion,app));
const CONFIG = {
    key:'koa:sess',  //cookie key(default is koa:sess)
    maxAge:86400000,  //cookie的过期时间 maxAge in ms(default is 1 days)
    overwrite:true,   //是否可以overwrite  (默认default true)
    httpOnly:true,  //cookie是否只有服务端可以访问 httpOnly or not (default true)
    signed:true,   //签名默认true
    rolling:false,  //在每次请求强行设置cookie,这将重置cookie过期时间
    renew:false,
}

// error handler
onerror(app)
app.use(session(CONFIG,app))

// middlewares

app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(cors(baseConfig.cors))

app.use(session(baseConfig.seesion,app))
app.use(passport.initialize())
app.use(passport.session())

app.use(views(__dirname + '/views', {
  //extension: 'nunjucks'
  map:{html:'nunjucks'}
}))

app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(news.routes(),news.allowedMethods())




// routes



// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});



module.exports = app